# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations

#########################################################################
## This is a samples controller
## - index is the default action of any application
## - user is required for authentication and authorization
## - download is for downloading files uploaded in the db (does streaming)
## - call exposes all registered services (none by default)
#########################################################################
from BeautifulSoup import BeautifulSoup
from gluon.html import web2pyHTMLParser
import urllib
import string
import re

brandNameList = db().select(db.productTest.ALL,distinct=True)
genderList = db().select(db.productTest.ALL,distinct=True)
typeList = db().select(db.productTest.ALL,distinct=True)

blist = set([row['brandName'] for row in brandNameList])
brandoptions = [OPTION(name) for name in blist]

glist = set([row['productGender'] for row in genderList])
genderoptions = [OPTION(gender) for gender in glist]

tlist = set([row['productType'] for row in typeList])
typeoptions = [OPTION(type) for type in tlist]

#brandoptions = set([OPTION(row['brandName']) for row in brandNameList])
#genderoptions = set([OPTION(row['productGender']) for row in genderList])
#typeoptions = set([OPTION(row['productType']) for row in typeList])
#brandoptions.insert(0,OPTION("Select Brand", _value=-1))
#genderoptions.insert(0,OPTION("Select Gender", _value=-1))
#typeoptions.insert(0,OPTION("Select Type", _value=-1))

def index():
    """
    example action using the internationalization operator T and flash
    rendered by views/default/index.html or views/generic.html
    """
    response.flash = "Welcome to web2py!"
    form = FORM(INPUT(_name='url_path', requires=IS_NOT_EMPTY()),
                SELECT('','Men','Women','Boy','Girl',_name='gender'),
                SELECT('','Clothing','Shoes','Accessories',_name='type'),
              INPUT(_type='submit'))
              
    if form.process().accepted:
        response.flash = 'Show the html content '  
        session.url=request.vars.url_path      
        session.gender=request.vars.gender      
        session.type=request.vars.type      
        ParseHtmlContent()
        #redirect(URL('show'))
    
    #soup = BeautifulSoup('<html><img src='' /></html>')
    #img = soup.find('img')
    return dict(message=form)

def manage():
    db.comments.image.writable = False
    grid = SQLFORM.smartgrid(db.productTest,linked_tables=['comments'])
    return dict(grid=grid)
    
def ParseHtmlContent():
    product={}
    #this list is used to record new added product so that we can show it
    newList=[]
    #data=urllib.urlopen(session.url).read()
    #soup = BeautifulSoup(data)
    #soup = BeautifulSoup('<a href="/clarks-un-galley-smokey-brown-nubuck-antique-brass" class="product product-8014235 style-836332 first r0-0-0 " data-style-id="836332" data-product-id="8014235"> <img src="http://a1.zassets.com/images/z/8/3/6/3/3/2/836332-p-LARGE_SEARCH.jpg" alt="Clarks &#45; Un.galley" class="productImg" /> <span class="brandName">Clarks</span> <span class="productName">Un.galley</span> <span class="price-6pm">$44.00</span> <span class="discount">(<strong>60% off</strong> MSRP $110.00)</span> </a> <a href="/product/7921734/color/328" class="product product-7921734 style-1017684 first r0-0-1 " data-style-id="1017684" data-product-id="7921734"> <img src="http://a1.zassets.com/images/z/1/0/1/7/6/8/1017684-p-LARGE_SEARCH.jpg" alt="Clarks &#45; Wave.Cruise" class="productImg" /> <span class="brandName">Clarks</span> <span class="productName">Wave.Cruise</span> <span class="price-6pm">$44.99</span> <span class="discount">(<strong>55% off</strong> MSRP $100.00)</span> </a> ')
    soup =BeautifulSoup('<a href="/nike-zoom-victory-xc-sprt-rd-snc-yellow-trsr-bl-white" class="product product-7938373 style-1800345 first r0-0-0 " data-style-id="1800345" data-product-id="7938373"> <img src="http://a1.zassets.com/images/z/1/8/0/0/3/4/1800345-p-LARGE_SEARCH.jpg" alt="Nike &#45; Zoom Victory XC" class="productImg" /> <span class="brandName">Nike</span> <span class="productName">Zoom Victory XC</span> <span class="price-6pm">$44.00</span> <span class="discount">(<strong>60% off</strong> MSRP $110.00)</span> </a>')
    l = soup.findAll('a', attrs={'class':re.compile("product.*")})
    for a in l:
        #pageLink is the unique in the productTest db

        product['pageLink'] = "http://www.6pm.com"+ a['href']
        product['thumbnailLink'] = a.find('img')['src']
        product['brandName'] = a.find('span', attrs={'class':"brandName"}).contents[0]
        product['productName'] = a.find('span', attrs={'class':"productName"}).contents[0]
        product['productStyle'] = string.strip(a['href'],r'/')
        product['salePrice'] = a.find('span', attrs={'class':"price-6pm"}).contents[0]
        product['origPrice'] = string.strip(a.find('span', attrs={'class':"discount"}).contents[2],')')


        sale=float(re.match(r".*\$(.*)",product['salePrice']).groups()[0])
        orig=float(re.match(r".*\$(.*)",product['origPrice']).groups()[0])
        product['discount'] = sale/orig*100
        #product['discount'] = sale


        item = db(db.productTest.pageLink==product['pageLink']).select().first()
        if item == None:
            #there is no such link, the product has not insert into the db, we should insert it

            #get the thumbnail image
            #imgData= urllib.urlopen(product['thumbnailLink']).read()
            #imgData= urllib.urlopen('http://i3.sinaimg.cn/IT/621/2009-06-26/U4672P2T621D1F19084DT20120710085623.jpg').read()
            imgData= open(r'D:\ProgramFiles\web2py\web2py\applications\welcome\controllers\test_image.jpg').read()

            id = db.productTest.insert(pageLink=product['pageLink'],thumbnail=imgData)
            #reget the item to update other filed
            item = db(db.productTest.id==id).select().first()
            newList.append(item)

            

        item.thumbnailLink = "%s" % product['thumbnailLink']
        item.brandName = "%s" % product['brandName']
        item.productName = "%s" % product['productName']
        item.productStyle = "%s" % product['productStyle']
        item.salePrice = "%s" % product['salePrice']
        item.origPrice = "%s" % product['origPrice']
        item.discount = "%s" % product['discount']

        if session.type != '':
            item.productType = "%s" % session.type
        if session.gender != '':
            item.productGender = "%s" % session.gender



        item.update_record()


    session.newList = newList
    redirect(URL('shownew'))
    return

def showproduct():
    product = db(db.productTest.id==request.args[0]).select().first()
    form=SQLFORM(db.productTest, product, deletable=True)
    if form.process().accepted:
        response.flash = 'form accepted'
    elif form.errors:
        response.flash = 'form has errors'
    return dict(product=product, form=form)

def updateallthumbnail():
    productList = db().select(db.productTest.ALL,orderby=db.productTest.productName)
    for product in productList:
        data=urllib.urlopen(product.thumbnailLink).read()
        product.thumbnail=data
        product.update_record()

    redirect(URL("showall"))

def updateproductthumbnail():
    product = db(db.productTest.id==request.args[0]).select().first()
    data=urllib.urlopen(product.thumbnailLink).read()
    product.thumbnail=data
    product.update_record()
    redirect(URL("showproduct",args=product.id))

def shownew():
    message="Show New added product"

    session.message = message
    session.list = session.newList
    redirect(URL('showlist'))
    #return dict(productList=productList)

def showfilter():
    return dict(message=args[0])

def showall():
    productList = db().select(db.productTest.ALL,orderby=db.productTest.productName)

    form = FORM(SELECT(OPTION("Select Brand",_value=-1),*brandoptions,_name='brand'),
                SELECT(OPTION("Select Gender",_value=-1),*genderoptions,_name='gender'),
                SELECT(OPTION("Select Type",_value=-1),*typeoptions,_name='type'),
                SELECT(OPTION('Sort By',_value=-1),'Name','Price','Brand','Discount',_name='sort'),
                INPUT(_type='submit'))
    if form.process().accepted:
        response.flash = 'Show filte product'  
        brand=request.vars.brand
        gender=request.vars.gender      
        productType=request.vars.type      
        sort = request.vars.sort

        if sort == 'Name':
            fpList=db().select(db.productTest.ALL, orderby=db.productTest.productName)
        elif sort == 'Brand':
            fpList=db().select(db.productTest.ALL, orderby=db.productTest.brandName)
        elif sort == 'Price':
            fpList=db().select(db.productTest.ALL, orderby=db.productTest.salePrice)
        elif sort == 'Discount':
            fpList=db().select(db.productTest.ALL, orderby=db.productTest.discount)
        elif sort == '-1':
            fpList=db().select(db.productTest.ALL)

        if brand != '-1':
            fpList=fpList.find(lambda row: row.brandName==brand)
        if gender != '-1':
            fpList=fpList.find(lambda row: row.productGender==gender)
        if productType != '-1':
            fpList=fpList.find(lambda row: row.productType==productType)

        return dict(productList=fpList,form=form)

    return dict(productList=productList,form=form)

def showlist():
    message=session.message
    productList = session.list
    return dict(message=message, productList=productList)

def show():
    content = ''
    product={}
    productList=[]
    data=urllib.urlopen(session.url).read()
    soup = BeautifulSoup(data)
    l = soup.findAll('a', attrs={'class':re.compile("product.*")})
    for a in l:
        content = content + "%s\n"%a['href']
        product={}
        product['pageLink'] = "http://www.6pm.com"+ a['href']
        product['type'] = string.strip(a['href'],r'/')
        product['thumbnailLink'] = a.find('img')['src']
        product['brandName'] = a.find('span', attrs={'class':"brandName"}).contents[0]
        product['productName'] = a.find('span', attrs={'class':"productName"}).contents[0]
        product['salePrice'] = a.find('span', attrs={'class':"price-6pm"}).contents[0]
        product['origPrice'] = string.strip(a.find('span', attrs={'class':"discount"}).contents[2],')')
        productList.append(product)
        
    return dict(data=l,productList=productList)

def getthumbnail():
    product = db(db.productTest.id==request.args[0]).select().first()
    response.headers["Content-Type"] = "image/jpeg"
    return product.thumbnail

def user():
    """
    exposes:
    http://..../[app]/default/user/login
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    use @auth.requires_login()
        @auth.requires_membership('group name')
        @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    """
    return dict(form=auth())


def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request,db)


def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    return service()


@auth.requires_signature()
def data():
    """
    http://..../[app]/default/data/tables
    http://..../[app]/default/data/create/[table]
    http://..../[app]/default/data/read/[table]/[id]
    http://..../[app]/default/data/update/[table]/[id]
    http://..../[app]/default/data/delete/[table]/[id]
    http://..../[app]/default/data/select/[table]
    http://..../[app]/default/data/search/[table]
    but URLs must be signed, i.e. linked with
      A('table',_href=URL('data/tables',user_signature=True))
    or with the signed load operator
      LOAD('default','data.load',args='tables',ajax=True,user_signature=True)
    """
    return dict(form=crud())
